<?php

namespace App\Http\Controllers\Dashboard;
use App\Http\Controllers\Controller;
use App\Models\Admin;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class AdminController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }
    public function login(Request $request) {
        $user_name  = $request->input('user_name');
        $password = $request->input('password');

        $check_data = Admin::where('name', $user_name)->first();
        if(empty($check_data)) {
            return ['code'=>1, 'msg'=>'error'];
        }
        if( $check_data['password'] != md5(md5($password).$check_data['encrypt']) ) {
            return ['code'=>1, 'msg'=>'error'];
        }

        $check_data->last_login_time = date('Y-m-d H:i:s', time());
        $check_data->last_login_ip = $request->ip();
        $check_data->api_token = md5($check_data->name.$check_data->last_login_time);
        $check_data->api_token_expire_time = date('Y-m-d H:i:s', time()+12*3600);
        $check_data->save();
        setcookie("api_token", $check_data->api_token, time()+12*3600, "/");
        return ['code'=>0, 'msg'=>'success'];
    }

    public function logout(){
        setcookie("api_token", '', time()+12*3600, "/");
        return view('admin.login');
    }
    //修改管理员密码
    public function updatePassword(Request $request){
        $old_password = $request->input("old_password");
        $new_password = $request->input("new_password");
        $admin = $manager = Auth::guard("admin")->user();
        $old_password = md5(md5($old_password).$admin->encrypt);
        if($old_password == $admin->password) {
            if(strlen($new_password)<6) {
                return ['code'=>2, 'msg'=>"new password is too short"];
            }
            $admin->encrypt = str_random('6');
            $admin->password = md5(md5($new_password).$admin->encrypt);
            $admin->save();
            return ['code'=>0, 'msg'=>"success"];
        }
        return ['code'=>1, 'msg'=>"invalid old password"];
    }

    //显示配置页面
    public function showSetting(){
        $settings = DB::table('settings')->get();
        return view('admin.setting', ['settings'=>$settings]);
    }
    //修改配置
    public function setting(Request $request, $id){
        $value = $request->input('value');
        DB::table('settings')->where('id', $id)->update(['value'=>$value]);
        return ['code'=>0, 'msg'=>"success"];;
    }
}